const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//获得key
function change_open(callback){
  var md5_ex = require('md5.js') 
  callback(md5_ex.hexMD5(""));
}

//判断是不是登陆状态
function is_login(callback){
    var res = wx.getStorageInfoSync();
    if (res.user_id){
      callback(res.user_id);
    }else{
      callback(false);
    }
}

var app = getApp();
// 上传图片
function chooseImg(user_id,callback) {
  var that = this;
  wx.chooseImage({
    count: 1, // 默认9 
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'],
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths[0];
      change_open(function (open) {
        var UploadTask =wx.uploadFile({
          url: app.globalData.host + '/Home/Teacher/upload_img', //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'imgs',
          formData: {
            'key': open,
            "uid":user_id
          },
          success: function (res) {
            var jsonObj = JSON.parse(res.data);
            callback(jsonObj);
          }
        })
        UploadTask.onProgressUpdate((res) => {
          if (res.progress < 100) {
            wx.showLoading({
              title: '已上传' + res.progress + '%',
            })
          } else {
            wx.hideLoading();
          }
        })
      })
    }
  });
}

//多图上传
function upload_imgs(uid, callback) {
  let that = this
  wx.chooseImage({
    count: 3, // 默认9 
    sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'],
    success: function (res) {
      change_open(function (open) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;
        for (let i = 0; i < tempFilePaths.length; i++) {
          var UploadTask = wx.uploadFile({
            url: app.globalData.host + '/Home/teacher/upload_img', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[i],
            name: 'imgs',
            formData: {
              'key': open,
              'uid': uid,
            },
            complete: function (res) {
              var jsonObj = JSON.parse(res.data)
              callback(jsonObj)
            }
          })
        }
        UploadTask.onProgressUpdate((res) => {
          if (res.progress < 100) {
            wx.showLoading({
              title: '已上传' + res.progress + '%',
            })
          } else {
            wx.hideLoading();
          }
        })
      })
      
    }
  });
}

/**
*json转换为map
*/
function jsonToMap(jsonStr) {
  return objToStrMap(JSON.parse(jsonStr));
}

/**
*对象转换为Map
*/
function objToStrMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}
/**
*map转化为对象（map所有键都是字符串，可以将其转换为对象）
*/
function strMapToObj(strMap) {
  let obj = Object.create(null);
  for (let [k, v] of strMap) {
    obj[k] = v;
  }
  return obj;
}

function postJson(url,param,callback){
  //列表数据获取  
  wx.request({
    url: app.globalData.host + url, //仅为示例，并非真实的接口地址
    data: param,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded' // 默认值
    },
    success(res) {
      var type = typeof res.data;
      if(type == 'string'){
        callback(JSON.parse(res.data.replace(/\ufeff/g, "")));
      }else{
        callback(res.data);
      }
        
    }
  })
}

//获取验证码倒计时
function countDown (time,callback) {
  setInterval(function (e) {
    if(time>0){
      time--;
    }else{
      clearInterval(e);
    }
    callback(time);
  }, 1000);
}

function putDate(res, obj) {
  obj.setData(res);
}

module.exports = {
  formatTime: formatTime,
  change_open: change_open,
  is_login: is_login,
  chooseImg: chooseImg,
  jsonToMap: jsonToMap,
  strMapToObj: strMapToObj,
  objToStrMap: objToStrMap,
  countDown: countDown,
  postJson: postJson,
  upload_imgs: upload_imgs,
  putDate: putDate,
}

